package org.linloong.modules.apis.common.service.impl;


import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.linloong.modules.apis.common.dto.DownloadDTO;
import org.linloong.modules.apis.common.enmus.ModelEnum;
import org.linloong.modules.apis.common.service.DownloadService;
import org.linloong.utils.MdToWordUtil;
import org.linloong.utils.ZipUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author dbo
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class DownloadServiceImpl implements DownloadService {

    private final MdToWordUtil mdToWordUtil;
    private final ZipUtils zipUtils;
    @Value("${zip.download.path}")
    private String zipDownloadPath;
    @Value("${zip.download.url}")
    private String downloadUrl;

    @Override
    public String downloadZip(List<DownloadDTO> data){

        String zipFileName = "智能决策方案_" + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss")) + ".zip";

        Path uploadDir = Paths.get(zipDownloadPath);
        if (!Files.exists(uploadDir)) {
            try {
                Files.createDirectories(uploadDir);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            log.info("创建上传目录：{}", zipDownloadPath);
        }

        // 构建完整的文件路径
        String filePath = uploadDir.resolve(zipFileName).toString();
        File zipFile = new File(filePath);

        byte[] zipBytes = null;
        try {
            Map<String, byte[]> map = new HashMap<>();
            for (DownloadDTO dto : data) {
                map.put(ModelEnum.getNameByCode(dto.getModelType()) +  ".docx",
                        mdToWordUtil.convertMarkdownToWord(dto.getMarkdownContent()));
            }
            zipBytes = zipUtils.zipBytes(map);
            try (FileOutputStream fos = new FileOutputStream(zipFile)) {
                fos.write(zipBytes);
            }
            log.info("成功生成方案文档压缩包：{}，大小：{}字节", zipFileName, zipBytes.length);
            return downloadUrl + zipFileName;
        } catch (Exception e) {
            log.error("生成方案文档压缩包失败：{}", e.getMessage(), e);
            throw new RuntimeException("生成下载文件失败：" + e.getMessage(), e);
        }
    }

}
